package backend

import (
	"github.com/gin-gonic/gin"
	"naio/constant"
	"naio/errs"
	"naio/pkg/jwt"
	"naio/serializer"
	"naio/validate"
	"net/http"
	"strings"
)

//OK

// @Summary 获取token
// @Produce json
// @Success 200 {object} string '{"code":0,"data":{},"msg":"ok"}'
// @Router /backend/login [post]
func (h *Handler) AuthLogin(c *gin.Context) {
	//panic(errs.NewMyAPIError(errs.ErrorAuthInfo, "这是一个自定义api错误"))
	//panic(errors.New("故意产生panic的"))
	loginParams := constant.BackendLoginRequest{}
	if err := c.ShouldBindJSON(&loginParams); err != nil {
		panic(errs.NewMyAPIError(errs.ErrorAuthInfo, err.Error()))
	}

	validator, _ := validate.Default()
	if check := validator.CheckStruct(loginParams); !check {
		panic(errs.NewMyAPIError(errs.ErrorAuthInfo, validator.GetAllErrorString()))
	}

	adminModel, err := h.service.AdminService.AdminLoginVaidate(loginParams.Username, loginParams.Password)
	if err != nil {
		panic(errs.NewMyAPIError(errs.ErrorAuthInfo, err.Error()))
	}

	accessToken, _ := jwt.CreateToken(adminModel.Id, adminModel.Role, constant.AccessTokenExpire)
	refreshToken, _ := jwt.CreateToken(adminModel.Id, adminModel.Role, constant.RefreshTokenExpire)

	res := serializer.SuccessMessage{Code: 0, Msg: "ok", Data: nil, RequestUrl: ""}
	res.Data = constant.BackendLoginResponse{AccessToken: accessToken, RefreshToken: refreshToken}
	res.RequestUrl = c.Request.Method + " " + c.Request.URL.String()
	c.JSON(http.StatusOK, res)
}

// @Summary 刷新token
// @Produce json
// @Success 200 {object} string '{"code":0,"data":{},"msg":"ok"}'
// @Router /backend/refresh_token [post]
func (h *Handler) AuthRefreshToken(c *gin.Context) {
	authorization := c.Request.Header.Get("Authorization")
	if authorization == "" {
		panic(errs.NewMyAPIError(errs.ErrorAuthTokenInvalid, errs.GetMsg(errs.ErrorAuthTokenInvalid)))
	}

	kv := strings.Split(authorization, " ")
	if len(kv) != 2 || kv[0] != "Bearer" {
		panic(errs.NewMyAPIError(errs.ErrorAuthTokenInvalid, errs.GetMsg(errs.ErrorAuthTokenInvalid)))
	}
	//token := kv[1]
	refreshToken := kv[1]
	if !jwt.ValidateToken(refreshToken) {
		panic(errs.NewMyAPIError(errs.ErrorAuthTokenInvalid, errs.GetMsg(errs.ErrorAuthTokenInvalid)))
	}
	payload, err := jwt.ParseToken(refreshToken)
	if err != nil {
		panic(errs.NewMyAPIError(errs.ErrorAuthTokenInvalid, err.Error()))
	}

	newAccessToken, _ := jwt.CreateToken(payload.Uid, payload.Role, constant.AccessTokenExpire)
	newRefreshToken, _ := jwt.CreateToken(payload.Uid, payload.Role, constant.RefreshTokenExpire)

	res := serializer.SuccessMessage{Code: 0, Msg: "ok", Data: nil, RequestUrl: ""}
	res.Data = constant.BackendLoginResponse{AccessToken: newAccessToken, RefreshToken: newRefreshToken}
	res.RequestUrl = c.Request.Method + " " + c.Request.URL.String()
	c.JSON(http.StatusOK, res)
}

// @Summary 获取用户信息
// @Produce json
// @Success 200 {object} string '{"code":0,"data":{},"msg":"ok"}'
// @Router /backend/auth/info [get]
func (h *Handler) AuthInfoFetch(c *gin.Context) {
	var id int
	uid, _ := c.Get("uid")
	if uid, ok := uid.(int); ok{
		id = uid
	}

	admin, err := h.service.AdminService.GetAuthInfoByID(id)
	if err != nil {
		panic(errs.NewMyAPIError(errs.ErrorAuth, err.Error()))
	}
	//auths := h.service.AdminService.GetGroupAuths(admin.Id)

	res := serializer.SuccessMessage{Code: 0, Msg: "ok", Data: nil, RequestUrl: ""}
	res.Data = constant.BackendAdminResponse{
		Id: admin.Id,
		Username: admin.Username,
		Status: admin.Status,
		Email: admin.Email,
		Mobile: admin.Mobile,
		Avatar: admin.Avatar,
		CreateTime: admin.CreateTime,
		UpdateTime: admin.UpdateTime,
		Role: admin.Role,
	}
	res.RequestUrl = c.Request.Method + " " + c.Request.URL.String()
	c.JSON(http.StatusOK, res)
}

func (h *Handler) AuthMenuFetch(c *gin.Context) {

}

func (h *Handler) AuthPasswordChange(c *gin.Context) {

}


// @Summary 获取权限菜单
// @Produce json
// @Success 200 {object} string '{"code":0,"data":{},"msg":"ok"}'
// @Router /backend/auth/menu [get]
//func (h *Handler) AuthMenuFetch(c *gin.Context) {
//	res := protocol.SuccessMessage{Code: 0, Msg: "ok", Data: nil}
//	adminId, _:= c.Get("id")
//	menu, err := h.service.AdminService.GetAuthMenuByID(adminId)
//	if err!=nil {
//		res.Msg = "error"
//		res.Code = -1
//		c.JSON(e.SUCCESS, res)
//		c.Abort()
//		return
//	}
//	res.Msg = "ok"
//	res.Data = menu
//	c.JSON(e.SUCCESS, res)
//	return
//}

// @Summary 退出
// @Produce json
// @Success 200 {object} string '{"code":0,"data":{},"msg":"ok"}'
// @Router /backend/logout [get]
func (h *Handler) AuthLogout(c *gin.Context) {

}

